package com.app.service.push;

import com.app.model.main.*;
import com.app.model.push.NotificationType;
import com.app.model.push.PushFlag;
import com.app.model.util.ArticleFlag;
import com.app.repository.interfaces.*;
import com.app.service.push.base.App;
import com.app.service.push.base.Demo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * Created by Lichaojie on 2017/4/14. It's a beautiful day.
 */
@Service
public class PushService {

    private Log log = LogFactory.getLog(PushService.class);

    @Autowired
    private CommentsOfArticleMapper commentsOfArticleMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private NotifyMapper notifyMapper;
    @Autowired
    private DeviceTokenMapper deviceTokenMapper;
    @Autowired
    private CommentsOfCommentsMapper commentsOfCommentsMapper;
    @Autowired
    private ApprovalMapper approvalMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private SystemMessageMapper systemMessageMapper;
    @Autowired
    private AccusationMapper accusationMapper;
    @Autowired
    private FavoriteItemMapper favoriteItemMapper;
    @Autowired
    private FavoritesMapper favoritesMapper;


    /**
     * 所有的单播通知（除举报被受理之后的通知）
     * @param object
     */
    public void pushNotification(Object object){

        Notify notify = new Notify();
        if(object instanceof CommentsOfArticle){
            CommentsOfArticle commentsOfArticle = (CommentsOfArticle)object;
            commentsOfArticle = commentsOfArticleMapper.selectByParam(commentsOfArticle.getUserId(),commentsOfArticle.getTime());
            Article article = articleMapper.selectByPrimaryKey(commentsOfArticle.getArticleId());
            notify.setObjectId(commentsOfArticle.getId())
                    .setReceiverId(article.getUserId())
                    .setSenderId(commentsOfArticle.getUserId())
                    .setType(article.getType() == ArticleFlag.HELP ? NotificationType.COMMENT_HELPARTICLE:NotificationType.COMMENT_SHAREARTICLE)
                    .setTime(commentsOfArticle.getTime());

        }else if(object instanceof CommentsOfComments){
            CommentsOfComments commentsOfComments = (CommentsOfComments)object;
            commentsOfComments = commentsOfCommentsMapper.selectByParam(commentsOfComments.getUserId(),commentsOfComments.getTime());
            CommentsOfArticle commentsOfArticle = commentsOfArticleMapper.selectByPrimaryKey(commentsOfComments.getCommentsId());
            notify.setObjectId(commentsOfComments.getId())
                    .setReceiverId(commentsOfArticle.getUserId())
                    .setSenderId(commentsOfComments.getUserId())
                    .setType(NotificationType.COMMENT_COMMENTS)
                    .setTime(commentsOfComments.getTime());

        }else if(object instanceof Approval){
            Approval approval = (Approval)object;
            approval = approvalMapper.selectByParam(approval.getUserId(),approval.getTime());

            notify.setObjectId(approval.getId())
                    .setSenderId(approval.getUserId())
                    .setTime(approval.getTime());

            byte approvalType = approval.getType();
            switch (approvalType){
                case 0:
                    Article article = articleMapper.selectByPrimaryKey(approval.getObjectId());
                    notify.setReceiverId(article.getUserId())
                            .setType(article.getType() == ArticleFlag.HELP ? NotificationType.APPROVAL_HELPARTICLE : NotificationType.APPROVAL_SHAREARTICLE);
                    break;
                case 1:
                    UserInfo userInfo = userInfoMapper.selectByPrimaryKey(approval.getObjectId());
                    notify.setReceiverId(userInfo.getId())
                            .setType(NotificationType.APPROVAL_USER);
                    break;
                case 2:
                    CommentsOfArticle commentsOfArticle = commentsOfArticleMapper.selectByPrimaryKey(approval.getObjectId());
                    notify.setReceiverId(commentsOfArticle.getUserId())
                            .setType(NotificationType.APPROVAL_COMMENTS);
                    break;
                case 3:
                    break;
                default:break;
            }
        }else if(object instanceof FavoriteItem){
            FavoriteItem favoriteItem = (FavoriteItem)object;
            favoriteItem = favoriteItemMapper.selectByFavoritesIdAndObjectId(favoriteItem.getFavoritesId(),favoriteItem.getObjectId());

            Favorites favorites = favoritesMapper.selectByPrimaryKey(favoriteItem.getFavoritesId());

            notify.setObjectId(favoriteItem.getId())
                    .setSenderId(favorites.getUserId())
                    .setTime(favoriteItem.getTime());

            byte favoriteType = favoriteItem.getType();
            switch (favoriteType){
                case 0:
                    Article article = articleMapper.selectByPrimaryKey(favoriteItem.getObjectId());
                    notify.setReceiverId(article.getUserId())
                            .setType(article.getType()==ArticleFlag.HELP?NotificationType.FAVORITE_HELPARTICLE:NotificationType.FAVORITE_SHAREARTICLE);
                    break;
                case 1:
                    break;
                case 2:
                    CommentsOfArticle commentsOfArticle = commentsOfArticleMapper.selectByPrimaryKey(favoriteItem.getObjectId());
                    notify.setReceiverId(commentsOfArticle.getUserId())
                            .setType(NotificationType.FAVORITE_COMMENTS);
                    break;
                case 3:
                    break;
                default:break;
            }
        }else if(object instanceof SystemMessage){
            //
        }else if(object instanceof Accusation){
            //
        }else{
            //
        }

        if(notifyMapper.insertSelective(notify) == 1){
            try {
                new Demo(PushFlag.APP_KEY,PushFlag.APP_MASTER_SECRET).sendAndroidUnicast(deviceTokenMapper.selectByUserId(notify.getReceiverId()).getDeviceTokenContent());
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }

    }

    /**
     * 推送系统消息
     * @param sMessage
     */
    public void pushSystemMessage(SystemMessage sMessage){
        SystemMessage systemMessage = systemMessageMapper.selectByParam(sMessage.getCreateTime());
        List<DeviceToken> dtList = deviceTokenMapper.getAllDeviceToken();
        for (DeviceToken deviceToken : dtList){
            Notify notify = new Notify();
            notify.setObjectId(systemMessage.getId())
                    .setReceiverId(deviceToken.getUserId())
                    .setSenderId(0l)
                    .setType(NotificationType.SYSTEM_MESSAGE)
                    .setTime(systemMessage.getCreateTime());
            notifyMapper.insertSelective(notify);//将系统消息加入到每个用户的通知列表中
        }

        try {
            new Demo(PushFlag.APP_KEY,PushFlag.APP_MASTER_SECRET).sendAndroidBroadcast();//广播系统消息
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 当有举报被提交时，通知举报者和被举报者
     * @param aaccusation
     */
    public void pushAccusation(Accusation aaccusation){
        //通知被举报用户
        Accusation accusation = accusationMapper.selectByParam(aaccusation.getSenderId(),aaccusation.getTime());

        Notify notify1 = new Notify();
        notify1.setObjectId(accusation.getId())
                .setSenderId(accusation.getSenderId())
                .setReceiverId(accusation.getReceiverId())
                .setType(NotificationType.ACCUSATION_NOTIFICATION)
                .setTime(accusation.getTime());

        //回复举报者
        Notify notify2 = new Notify();
        notify2.setObjectId(accusation.getId())
                .setReceiverId(accusation.getSenderId())
                .setSenderId(0l)
                .setType(NotificationType.ACCUSATION_RECEIVED_REPLY)
                .setTime(accusation.getTime());

        if(notifyMapper.insertSelective(notify1) == 1 && notifyMapper.insertSelective(notify2) == 1){
            try {
                new Demo(PushFlag.APP_KEY,PushFlag.APP_MASTER_SECRET).sendAndroidUnicast(deviceTokenMapper.selectByUserId(notify1.getReceiverId()).getDeviceTokenContent());
                new Demo(PushFlag.APP_KEY,PushFlag.APP_MASTER_SECRET).sendAndroidUnicast(deviceTokenMapper.selectByUserId(notify2.getReceiverId()).getDeviceTokenContent());
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    /**
     * 举报被受理后给被举报人通知结果
     * @param aaccusation
     */
    public void pushAccusationResult(Accusation aaccusation){
        Accusation accusation = accusationMapper.selectByParam(aaccusation.getSenderId(),aaccusation.getTime());

        //通知举报者
        Notify notify = new Notify();
        notify.setObjectId(accusation.getId())
                .setReceiverId(aaccusation.getReceiverId())
                .setSenderId(accusation.getSenderId())
                .setType(NotificationType.ACCUSATION_HANDLE_RESULT)
                .setTime(Long.toString(System.currentTimeMillis()));

    }



}
